import 'dart:developer';
import 'dart:io';
import 'dart:typed_data';
// import 'dart:typed_data';
// import 'dart:typed_data';

// import 'package:extended_image/extended_image.dart';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:photo_manager/photo_manager.dart';
import 'EditPage.dart';
import 'utils.dart';

void main() {
  SystemUiOverlayStyle style = SystemUiOverlayStyle(statusBarColor: Colors.transparent);
  SystemChrome.setSystemUIOverlayStyle(style);
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key,}) : super(key: key);
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<File> picList = [];
  int crossCount = 2;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp,DeviceOrientation.portraitDown]);
    loadData();
  }
  loadData()async{
    var dir = await getExternalStorageDirectory();
    // findFile(dir.path);
    log(dir.path);
    for(var i in dir.listSync()){
      if(!FileSystemEntity.isDirectorySync(i.path)){
        picList.add(i);
      }
    }
    setState(() {

    });
  }
  findFile(String path){
    var directory = Directory(path);
    for(var i in directory.listSync()){
      if(FileSystemEntity.isDirectorySync(i.path)){
        findFile(i.path);
      }else{
        picList.add(File(i.path));
      }
    }
    setState(() {

    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xff334455),
      appBar: AppBar(
        brightness: Brightness.dark,
        elevation: 0,
        backgroundColor: Colors.transparent,
        title: Text("Picture Editor",style: TextStyle(color: Colors.white),),
      ),
      body: picList.isEmpty?Center(
        child: Text("Select a Picture",style: TextStyle(color: Colors.white),),
      ):Column(
        children: [
          Container(
            width: double.infinity,
              margin: EdgeInsets.only(left: 16,top: 20),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("Histories",style: TextStyle(color: Colors.white,fontWeight: FontWeight.w500),),
                  TextButton(onPressed: (){
                    setState(() {
                      if(crossCount<4){
                        crossCount++;
                      }else if(crossCount==4){
                        crossCount =2;
                      }
                    });
                  }, child: Icon(Icons.grid_on_rounded))
                ],
              )
          ),
          Expanded(child: GridView(
            physics: BouncingScrollPhysics(),
            padding: EdgeInsets.symmetric(horizontal: 16),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: crossCount,
                childAspectRatio: 9/16,
                mainAxisSpacing: 15,
                crossAxisSpacing: 10
            ),
            children: picList.map((e) => GestureDetector(
              onTap: (){
                Navigator.push(context, MaterialPageRoute(builder: (_)=>EditPage(e))).then((value){
                  if(value != null){
                    picList.add(value);
                    setState(() {

                    });
                  }
                });
              },
              child: Container(
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.white,width: 3),
                    borderRadius: BorderRadius.circular(7),
                  ),
                  child: ClipRRect(
                      borderRadius: BorderRadius.circular(4),
                      child: Image.file(e,fit: BoxFit.cover,filterQuality: FilterQuality.low,))),
            )).toList(),
          ))
        ],
      ),
      bottomNavigationBar: BottomAppBar(
        color: Color(0xffeeeeee),
        child: Row(
          children: [
            Expanded(child: FlatButtonWidthIcon(icon: Icons.file_copy_rounded,text: "Gallery",onPress:()=>selectImage(0),)),
            Expanded(child: FlatButtonWidthIcon(icon: Icons.camera_alt_rounded,text: "Camera",onPress:()=>selectImage(1),)),
          ],
        ),
      ),
    );
  }
  selectImage(int type){
    ImagePicker().getImage(source: type==1?ImageSource.camera:ImageSource.gallery).then((value){
      if(value!=null){
        Navigator.push(context, MaterialPageRoute(builder: (_)=>EditPage(value))).then((value){
          if(value!=null){
            picList.add(value);
            setState(() {

            });
          }
        });
      }
    });
  }
}
